package gods.bubble.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

public class SimpleFileIOUtil {

	public static String fileToString(String filePath, String encoding)
			throws IOException {
		return fileToString(new File(filePath), encoding);
	}

	public static String fileToString(File file, String encoding)
			throws IOException {
		InputStreamReader reader = new InputStreamReader(new FileInputStream(
				file), encoding);
		StringWriter writer = new StringWriter();
		// 将输入流写入输出流
		char[] buffer = new char[1024];
		int n = 0;
		while (-1 != (n = reader.read(buffer))) {
			writer.write(buffer, 0, n);
		}
		reader.close();
//		System.out.println(writer.toString());
		// 返回转换结果
		return writer.toString();
	}

	public static void stringToFile(String text, String filePath,
			String encoding) throws UnsupportedEncodingException,
			FileNotFoundException {
		stringToFile(text, new File(filePath), encoding);
	}

	public static void stringToFile(String text, File file, String encoding)
			throws UnsupportedEncodingException, FileNotFoundException {
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(
				new FileOutputStream(file), encoding));
		pw.print(text);
		pw.close();
	}
}
